import 'package:changxindianzishangwu/dao/select_user_dao.dart';
import 'package:changxindianzishangwu/model/select_user.dart';
import 'package:changxindianzishangwu/pages/contacts/user_cart/user_check_page.dart';
import 'package:changxindianzishangwu/widget/noting_user_wiget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

class SearchUserIdPage extends StatefulWidget {
  SearchUserIdPage({Key key}) : super(key: key);

  @override
  _SearchUserIdPageState createState() => _SearchUserIdPageState();
}

class _SearchUserIdPageState extends State<SearchUserIdPage> {
  var userId = "";
  var flag = false; //控制查询组件
  V2TimUserFullInfo _userEntity;
  List userIDList;
  List<V2TimUserFullInfo> userEntity;

  V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
  final TextEditingController _controller = new TextEditingController();

  List<V2TimFriendInfoResult> friendInfoResult;
  SelectUser user;
  getServiceData() async {
    EasyLoading.show(status: "查询中...");
    user = await SelectUserDao.getUserInfo(userId);
    if (user.data.length == 0) {
      EasyLoading.dismiss();
      setState(() {
        flag = true;
      });
    } else {
      EasyLoading.dismiss();
      _findUserFriends();
    }
  }

  @override
  void dispose() {
    super.dispose();
    EasyLoading.dismiss();
  }

  _findUserFriends()async {
    try {
      print(user.data[0].userId);
     V2TimValueCallback<List<V2TimFriendInfoResult>>
          v2TimFriendInfoResult = await timManager.v2TIMFriendshipManager
              .getFriendsInfo(userIDList: [user.data[0].userId.toString()]);
      userEntity = [];
      if (v2TimFriendInfoResult.data.length == 0) {
        setState(() {
          flag = true;
        });
      } else {
        friendInfoResult = v2TimFriendInfoResult.data;
        friendInfoResult.forEach((element) {
          userEntity.add(element.friendInfo.userProfile);
        });
        getData();
        setState(() {
          flag = false;
        });
      }
    } catch (e) {
      if (userEntity == null) {
        print("object");
        getData();
        setState(() {
          flag = true;
        });
      }
      print(e);
    }
  }

  getData() {
    if (userEntity != null && userEntity.length > 0) {
      for (var i = 0; i < userEntity.length; i++) {
        print(userEntity.length);
        _userEntity = userEntity[0];
        print(userEntity[i].toJson());
      }
      setState(() {
        flag = false;
      });
      Get.to(() => UserCheckPage(
            userId: user.data[0].userId.toString(),
            ziyuId: user.data[0].account.toString(),
            userEntity: _userEntity,
          ));
    } else {
      setState(() {
        flag = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "查找用户",
          style:
              TextStyle(fontSize: ScreenUtil().setSp(15), color: Colors.black),
        ),
      ),
      body: Container(
        color: Colors.white,
        child: ListView(
          children: [
            InkWell(
              onTap: () {},
              child: Container(
                height: ScreenUtil().setHeight(32),
                alignment: Alignment.center,
                padding: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
                margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(10),
                    right: ScreenUtil().setWidth(15)),
                decoration: BoxDecoration(
                    color: Color.fromRGBO(241, 241, 241, 1),
                    borderRadius: BorderRadius.circular(6)),
                child: TextField(
                  onSubmitted: (value) {
                    getServiceData();
                  },
                  cursorColor: Colors.lightBlueAccent,
                  autofocus: false,
                  controller: _controller,
                  onChanged: (value) {
                    setState(() {
                      userId = value;
                    });
                    //TODO 需要优化
                  },
                  textAlign: TextAlign.center,
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "手机号/用户ID",
                      hintStyle: TextStyle(
                        fontSize: ScreenUtil().setSp(13),
                      )),
                ),
              ),
            ),
            userId != ""
                ? InkWell(
                    onTap: () {
                      getServiceData();
                    },
                    child: Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                      child: ListTile(
                          leading: Container(
                            height: ScreenUtil().setHeight(22),
                            width: ScreenUtil().setWidth(22),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2),
                              color: Color.fromRGBO(0, 220, 169, 1),
                            ),
                            child: Image.asset(
                              "images/search.png",
                              height: ScreenUtil().setHeight(16),
                              width: ScreenUtil().setWidth(16),
                              fit: BoxFit.contain,
                              color: Colors.white,
                            ),
                          ),
                          title: Container(
                            margin:
                                EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                            child: Text(
                              "搜索：" + userId,
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(16),
                              ),
                            ),
                          ),
                          trailing: Icon(Icons.keyboard_arrow_right)),
                    ),
                  )
                : Container(),
            flag
                ? Container(
                    margin: EdgeInsets.only(top: ScreenUtil().setHeight(163)),
                    child: NotingUserWiget(),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}
